import React, {PropTypes} from 'react';
import gql from 'graphql-tag';
import {connect} from 'react-apollo';
import {
    Row, Col, Collapse,
    Button, Icon
} from 'antd';
import Base from '../../base';
import Tables from './table';
import {stop} from '../../util';

const mapQueriesToProps = ({ownProps: props}) => ({
    data: {
        query: gql`
            query get($connection: String!) {
                databases(connection: $connection) {
                    name
                }
            }
        `,
        variables: {
            connection: props.connection.name
        }
    }
});

@connect({mapQueriesToProps})
export default class Database extends Base {
    static propTypes = {
        connection: PropTypes.object.isRequired,
        setReload: PropTypes.func.isRequired
    };

    state = {active: this.context.params.db};

    init() {
        this.data = 'databases';
    }

    mount() {
        this.props.setReload(this.props.data.refetch);
    }

    onReload(e) {
        stop(e);
        if (this.reload) {
            this.reload();
        }
    }

    done(data) {
        return (
            <Collapse accordion defaultActiveKey={this.state.active}>
                {data.map(({name: database}) => {
                    const header = (
                        <Row type="flex" align="middle">
                            <Col span="12">{database}</Col>
                            <Col span="12" className="right padding-right">
                                <Button
                                    onClick={this.onReload.bind(this)}
                                    type="flat blue"
                                    size="small"
                                >
                                    <Icon type="reload"/>
                                </Button>
                            </Col>
                        </Row>
                    );
                    return (
                        <Collapse.Panel key={database} header={header}>
                            <Tables
                                database={database}
                                connection={this.props.connection.name}
                                setReload={reload => {this.reload = reload;}}
                            />
                        </Collapse.Panel>
                    );
                })}
            </Collapse>
        );
    }
}
